<template>
  <div class="wrap">
    <div class="search">
      <div class="mgb20">
        <user-check-box
          @change="changeOption"
          v-model="queryParams.userIds"
          :disdisabled="loading"
          :filter-stop="true"
          @apiUserFinish="changeOption"></user-check-box>

      </div>
      <div class="search-group">
        <diy-date v-model="queryParams.times" @change="changeOption" :date-type="2" :set-month-type="1" :disdisabled="loading"></diy-date>
        <div class="right">
          <template v-if="tab === 'order'">
            <export-button :func="getSettleOrderList" :query-params="queryParams" :exportType="'settlement'" :getTotal="total"></export-button>
          </template>
          <el-button @click="createPayment" :loading="paymentLoading" type="primary">{{$t('data.Generate settlement documents')}}</el-button>
        </div>
      </div>
    </div>
    <div class="content-table">
      <el-tabs v-model="tab" @tab-click="handleClick">
        <el-tab-pane :label="$t('data.orderData')" name="order"></el-tab-pane>
        <el-tab-pane :label="$t('data.理货数据')" name="shipment"></el-tab-pane>
        <el-tab-pane :label="$t('data.送仓数据')" name="middle"></el-tab-pane>
        <el-tab-pane :label="$t('data.调货数据')" name="transfer"></el-tab-pane>
        <el-tab-pane :label="$t('data.贴标数据')" name="label"></el-tab-pane>
        <el-tab-pane :label="$t('data.warehouseData')" name="storage"></el-tab-pane>
      </el-tabs>
      <div class="table">

        <div v-show="tab === 'order'">
          <el-table
            :data="orderData"
            :border="true"
            v-loading="loading"
            stripe
            show-summary
            :summary-method="getSummaries1"
            :default-sort="defaultSort"
            @sort-change="handleSortChange"
            v-tableHeight="{bottomOffset: 80}"
            height="100px"
            ref="orderTableData"
          >
            <el-table-column
              prop="orderId"
              :label="$t('table.orderId')"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="accountType"
              :label="$t('table.platform')"
              align="center"
              v-if="$store.getters.platformNum > 1"
            >
            </el-table-column>
            <el-table-column
              prop="userAccount"
              :label="$t('common.user')"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="showName"
              :label="$t('table.store')"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="num"
              :label="$t('table.productQuantity')"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="stickerPrice"
              :label="$t('table.Total sticker fee')"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="spStickerPrice"
              :label="$t('table.Unit price of sticker')"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="stickerAppend"
              :label="$t('table.Continuation cost')"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="logisticTypePrice"
              :label="$t('table.Special courier fees')"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="packagePrice"
              :label="$t('table.Packaging service fees')"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="createdDate"
              :label="$t('table.createTime')"
              align="center"
              sortable="custom"
              :sort-orders="sortOrders"
            >
            </el-table-column>
            <el-table-column
              prop="stickerTime"
              :label="$t('table.placementTime')"
              align="center"
              sortable="custom"
              :sort-orders="sortOrders"
            >
            </el-table-column>
            <el-table-column
              prop="finishTime"
              :label="$t('table.Completion/Cancellation/Return Time')"
              align="center"
            >
              <template slot-scope="{row}">
                {{row.refundDate || row.cancelDate || row.finishDate || '-'}}
              </template>
            </el-table-column>
          </el-table>
        </div>

        <div v-show="tab === 'storage'">
          <el-table
            :data="storageData"
            v-loading="loading"
            :border="true"
            stripe
            show-summary
            :summary-method="getSummaries2"
            v-tableHeight="{bottomOffset: 80}"
            height="100px"
            ref="storageTableData"
          >
            <el-table-column
              prop="date"
              :label="$t('table.date')"
              align="center"
            >
            </el-table-column>
            <el-table-column
              v-for="item in weightRangeList"
              :key="item.rangeId"
              :prop="'detail' + item.rangeId"
              :label="item.weightName + (item.stockField === stockField.stockNum ? `（${$t('个')}）` : `（${$t('箱')}）`)"
              align="center"
            >
              <template v-slot="{row}">
                <template v-if="row['detail' + item.rangeId]">
                  <span>{{row['detail' + item.rangeId].calNum}}</span>
                </template>
                <template v-else>
                  -
                </template>
              </template>
            </el-table-column>


            <el-table-column
              prop="totalFee"
              :label="$t('table.totalStorageCost')"
              align="center"
            >
            </el-table-column>
          </el-table>
        </div>

        <div v-show="tab === 'middle'">
          <el-table
            :data="middleData"
            :border="true"
            v-loading="loading"
            stripe
            show-summary
            :summary-method="getSummaries3"
            v-tableHeight="{bottomOffset: 80}"
            height="100px"
            ref="middleTableData"
          >
            <el-table-column
              prop="workNo"
              :label="$t('table.送仓单号')"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="userAccount"
              :label="$t('common.user')"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="accountName"
              :label="$t('table.store')"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="boxNum"
              :label="$t('table.箱子数量')"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="rlSkuNum"
              :label="$t('table.SKU数量')"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="rlGoodsNum"
              :label="$t('table.productQuantity')"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="transfer2warehouse"
              :label="$t('table.送仓费用（元）')"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="boxLabelFee"
              :label="$t('table.贴外箱标费用（元）')"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="charteredCarFee"
              :label="$t('table.包车费用（元）')"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="createTime"
              :label="$t('table.createTime2')"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="sendTime"
              :label="$t('table.送仓时间')"
              align="center"
            >
              <template v-slot="{row}">
                {{row.sendTime || '-'}}
              </template>
            </el-table-column>
          </el-table>
        </div>

        <div v-show="tab === 'transfer'">
          <el-table
            :data="transferData"
            :border="true"
            v-loading="loading"
            stripe
            show-summary
            :summary-method="getSummaries3"
            v-tableHeight="{bottomOffset: 80}"
            height="100px"
            ref="transferTableData"
          >
            <el-table-column
              prop="workNo"
              label="调货单号"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="userAccount"
              :label="$t('common.user')"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="accountName"
              :label="$t('table.store')"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="boxNum"
              :label="$t('table.箱子数量')"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="rlSkuNum"
              :label="$t('table.SKU数量')"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="rlGoodsNum"
              :label="$t('table.productQuantity')"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="rlTotalTransferFee"
              :label="$t('table.调货费用（元）')"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="createTime"
              :label="$t('table.createTime2')"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="finishTime"
              :label="$t('table.完成时间')"
              align="center"
            >
              <template v-slot="{row}">
                {{row.finishTime || '-'}}
              </template>
            </el-table-column>
          </el-table>
        </div>

        <div v-show="tab === 'label'">
          <el-table
            :data="labelData"
            :border="true"
            v-loading="loading"
            stripe
            show-summary
            :summary-method="getSummaries3"
            v-tableHeight="{bottomOffset: 80}"
            height="100px"
            ref="labelTableData"
          >
            <el-table-column
              prop="labelNo"
              :label="$t('table.贴标单号')"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="userAccount"
              :label="$t('common.user')"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="rlSkuNum"
              :label="$t('table.SKU数量')"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="rlGoodsNum"
              :label="$t('table.productQuantity')"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="rlTotalFee"
              :label="$t('table.贴SKU标费用（元）')"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="createTime"
              :label="$t('table.createTime2')"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="finishTime"
              :label="$t('table.完成时间')"
              align="center"
            >
              <template v-slot="{row}">
                {{row.finishTime || '-'}}
              </template>
            </el-table-column>
          </el-table>
        </div>

        <div v-show="tab === 'shipment'">
          <el-table
            :data="shipmentData"
            :border="true"
            v-loading="loading"
            stripe
            show-summary
            :summary-method="getSummaries4"
            v-tableHeight="{bottomOffset: 80}"
            height="100px"
            ref="shipmentTableData"
          >
            <el-table-column
              prop="shipmentNo"
              :label="$t('table.shipmentNumber')"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="userAccount"
              :label="$t('common.user')"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="rlBoxNum"
              :label="$t('table.箱子数量')"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="rlSkuNum"
              :label="$t('table.SKU数量')"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="rlGoodsNum"
              :label="$t('table.productQuantity')"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="rlListingFee"
              :label="$t('table.上架费用（元）')"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="combinationFee"
              :label="$t('table.组装费用（元）')"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="inWarehouseFee"
              label="入仓费用（元）"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="fullInWarehouseFee"
              label="直送费用（元）"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="createTime"
              :label="$t('table.createTime2')"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="confirmTime"
              :label="$t('table.warehousingTime')"
              align="center"
            >
            </el-table-column>
          </el-table>
        </div>

        <div class="page-wrap" v-if="tab !== 'storage'">
          <el-pagination
            @current-change="getData"
            :current-page.sync="queryParams.page"
            :page-size="queryParams.pageSize"
            :total="total"
            layout="total, prev, pager, next, jumper"
          >
          </el-pagination>
        </div>


      </div>
    </div>
  </div>
</template>

<script>
import {
  accountIndex, createPayment,
  getDateIncome,
  getIndex, getLabelOrderList, getMiddleOrderList,
  getSettleOrderList,
  getSettleStorageList, getShipmentList, getTransferOrderList,
} from "@/api/statistics";
import {dateFormat, getTargetDate} from "@/utils/common";
import DiyDate from "@/views/statistics/components/DiyDate.vue";
import UserCheckBox from "@/views/shipment/components/UserCheckBox.vue";
import ExportButton from "@/views/order/components/ExportButton.vue";
import {stockField} from "@/utils/stock";

export default {
  name: "settlement",
  components: {ExportButton, UserCheckBox, DiyDate},
  computed:{
    tableData(){
      const tableData = [];
      this.data.forEach(item=>{
        if(this.queryParams.showType === 1){
          if(item.orderNum === 0 && item.stickerNum === 0 && item.totalPrice === 0){
            return
          }
        }
        tableData.push(item)
      })
      return tableData;
    },
    tableAccountData(){
      const tableData = [];
      this.accountData.forEach(item=>{
        if(this.queryParams.showType === 1){
          if(item.orderNum === 0 && item.stickerNum === 0 && item.cost === 0){
            return
          }
        }
        tableData.push(item)
      })
      return tableData;
    }
  },
  data(){
    return {
      queryParams:{
        userIds: [-1],
        times:[], // 日期
        keyword:'', // 搜索关键字
        page: 1,
        pageSize: 20,
      },
      cardNumber: {
        userNum: 0,
        accountNum: 0,
        stickerIncome: 0,
        stickerNum: 0,
        storageIncome: 0,
        income: 0,
      }, // 卡片数值
      minDate: null,
      // 日期选项
      orderData: [

      ],
      storageData: [

      ],
      weightRangeList: [], // 重量范围
      apiTimes: 0, // 用于刷新表格
      stockField,

      orderSum:{
        num: 0, // 商品总数
        stickerPrice: 0, // 总贴单金额
        logisticTypePrice: 0, // 总贴单金额
        packagePrice: 0, // 总贴单金额
        spStickerPrice: 0, // 总贴单金额
        stickerAppend: 0, // 总贴单金额
      },
      storageSum: {
        totalFee: 0,
      },
      accountNum: 0,
      loading: false,
      paymentLoading: false,
      total: 0,
      tab: 'order',
      // 大货中转
      middleData: [],
      transferData: [],
      labelData: [],
      goodsMiddleSum: {
        sumSkuNum: 0,
        sumGoodsNum: 0,
        sumBoxFee: 0,
        sumFee: 0,
        sumCar: 0,
      },
      shipmentData: [],

      sortOrders: ['descending', 'ascending', null],

      defaultSort:{
        prop: 'createdDate',
        order: 'descending'
      },
    }
  },
  created() {
    this.queryParams.orderBy = this.defaultSort.order
    this.queryParams.orderField = this.defaultSort.prop
    // const date = new Date()
    //


    let now = getTargetDate(); // 获取当前日期时间
    let startDate = new Date(now.getFullYear(), now.getMonth(), 1); // 获取本月第一天的日期时间
    let endDate = new Date(now.getFullYear(), now.getMonth() + 1, 0, 23, 59, 59);

    let endTime = dateFormat('yyyy-MM-dd',endDate)
    // date.setDate(date.getDate() - 30)
    let startTime = dateFormat('yyyy-MM-dd',startDate)

    this.queryParams.times = [startTime,endTime]
    // this.getData()
  },
  updated () {
    this.$nextTick(() => {
      this.$refs['orderTableData'].doLayout();
      this.$refs['shipmentTableData'].doLayout();
      this.$refs['middleTableData'].doLayout();
      this.$refs['transferTableData'].doLayout();
      this.$refs['labelTableData'].doLayout();
      this.$refs['storageTableData'].doLayout();
    })
  },
  methods:{
    getSettleOrderList,
    // 切换tab
    handleClick(){
      this.getData()
    },
    disableFunc(time){
      return true
    },
    getData(){
      if(this.queryParams.times === null || this.queryParams.times.length === 0){
        this.data = [];
        return;
      }
      this.loading = true
      if(this.tab === 'order'){
        getSettleOrderList(this.queryParams)
          .then(res=>{
            this.loading = false
            this.orderData = res.data
            this.total = res.info.total;
            this.orderSum.logisticTypePrice = res.info.sumData.logisticTypePrice
            this.orderSum.num = res.info.sumData.num
            this.orderSum.packagePrice = res.info.sumData.packagePrice
            this.orderSum.spStickerPrice = res.info.sumData.spStickerPrice
            this.orderSum.stickerAppend = res.info.sumData.stickerAppend
            this.orderSum.stickerPrice = res.info.sumData.stickerPrice
          })
      }
      if(this.tab === 'storage'){
        getSettleStorageList(this.queryParams)
          .then(res=>{
            this.loading = false
            this.storageData = res.data
            this.weightRangeList = res.info.weightRangeList
            this.apiTimes++;
          })
      }
      if(this.tab === 'middle'){
        getMiddleOrderList(this.queryParams)
          .then(res=>{
            this.loading = false
            this.total = res.info.total;
            this.middleData = res.data
            this.goodsMiddleSum.sumSkuNum = res.info.sumSkuNum
            this.goodsMiddleSum.sumGoodsNum = res.info.sumGoodsNum
            this.goodsMiddleSum.sumFee = res.info.sumFee
            this.goodsMiddleSum.sumBoxFee = res.info.sumBoxFee
          })
      }
      if(this.tab === 'transfer'){
        getTransferOrderList(this.queryParams)
          .then(res=>{
            this.loading = false
            this.total = res.info.total;
            this.transferData = res.data
            this.goodsMiddleSum.sumSkuNum = res.info.sumSkuNum
            this.goodsMiddleSum.sumGoodsNum = res.info.sumGoodsNum
            this.goodsMiddleSum.sumFee = res.info.sumFee
            this.goodsMiddleSum.sumBoxFee = 0
          })
      }
      if(this.tab === 'label'){
        getLabelOrderList(this.queryParams)
          .then(res=>{
            this.loading = false
            this.total = res.info.total;
            this.labelData = res.data
            this.goodsMiddleSum.sumSkuNum = res.info.sumSkuNum
            this.goodsMiddleSum.sumGoodsNum = res.info.sumGoodsNum
            this.goodsMiddleSum.sumFee = res.info.sumFee
            this.goodsMiddleSum.sumBoxFee = 0
          })
      }
      if(this.tab === 'shipment'){
        getShipmentList(this.queryParams)
          .then(res=>{
            this.loading = false
            this.total = res.info.total
            this.shipmentData = res.data
          })
      }
    },
    changeOption(){
      this.queryParams.page = 1;
      this.getData();
    },
    getSummaries1(param){
      const { columns, data } = param;
      const sums = [];

      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = this.$t('table.sum');
          return;
        }
        if(column.property === 'stickerPrice'){
          sums[index] = this.orderSum.stickerPrice;
        }else if(column.property === 'spStickerPrice'){
          sums[index] = this.orderSum.spStickerPrice
        }else if(column.property === 'stickerAppend'){
          sums[index] = this.orderSum.stickerAppend
        }else if(column.property === 'logisticTypePrice'){
          sums[index] = this.orderSum.logisticTypePrice
        }else if(column.property === 'packagePrice'){
          sums[index] = this.orderSum.packagePrice
        }else{
          sums[index] = '-'
        }
      });
      return sums;
    },
    getSummaries2(param){
      const { columns, data } = param;
      const sums = [];

      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = this.$t('table.sum');
          return;
        }
        if(index === columns.length - 1){
          sums[index] = data.reduce((prev, curr)=>{
            return prev + Number(curr.totalFee)
          },0)
        }else{
          sums[index] = data.reduce((prev,curr)=>{
            return prev + (curr[column.property] ? Number(curr[column.property].calNum) : 0)
          },0)
        }

      });
      return sums;
    },
    getSummaries3(param){
      const { columns, data } = param;
      const sums = [];

      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = this.$t('table.sum');
          return;
        }
        if(column.property === 'rlSkuNum'){
          sums[index] = this.goodsMiddleSum.sumSkuNum;
        }else if(column.property === 'rlGoodsNum'){
          sums[index] = this.goodsMiddleSum.sumGoodsNum
        }else if(column.property === 'transfer2warehouse'){
          sums[index] = this.goodsMiddleSum.sumFee
        }else if(column.property === 'boxLabelFee'){
          sums[index] = this.goodsMiddleSum.sumBoxFee
        } else if(column.property === 'rlTotalFee' || column.property === 'rlTotalTransferFee'){
          sums[index] = this.goodsMiddleSum.sumFee + this.goodsMiddleSum.sumBoxFee
        } else if(column.property === 'charteredCarFee'){
          sums[index] = this.goodsMiddleSum.sumCar
        }else{
          sums[index] = '-'
        }
      });
      return sums;
    },
    getSummaries4(param){
      const { columns, data } = param;
      const sums = [];

      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = this.$t('table.sum');
          return;
        }
        const arr = ['rlBoxNum','rlSkuNum','rlGoodsNum','rlListingFee','combinationFee', 'fullInWarehouseFee', 'inWarehouseFee'];
        if(arr.indexOf(column.property) !== -1){
          const values = data.map(item => Number(item[column.property]));
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);

          } else {
            sums[index] = '-';
          }
        }else {
          sums[index] = '-';
        }

      });
      return sums;
    },
    createPayment(){
      this.paymentLoading = true
      createPayment(this.queryParams)
        .then(res=>{
          this.paymentLoading = false
          if(res.error === 0){
            res.data.forEach(paymentId=>{
              const { href } = this.$router.resolve({
                name: 'settlementInfo',
                query: {
                  id: paymentId,
                }
              })
              window.open(href,'_blank')
            })
          }else{
            this.$errorMessage(res.message)
          }
        })
    },
    //排序
    handleSortChange(column){
      this.queryParams.orderBy = ''
      this.queryParams.orderField = ''
      if(column.order){
        this.queryParams.orderBy = column.order
        this.queryParams.orderField = column.prop
      }
      this.queryParams.page = 1;
      this.getData()
    },
  }
}
</script>

<style scoped lang="scss">
.wrap {
  padding: 30px 30px;
  .header{
    display: flex;
    justify-content: space-between;
  }
  .content{
    padding: 20px 0 0;
  }
  .search{
    .search-group{
      display: flex;
      justify-content: space-between;
      flex-direction: row;
    }
  }
}
.today-card{
  background: inherit;
  background-color: #4A89DC;
}
.yesterday-card{
  background: inherit;
  background-color: #5D9CEC;
}
.user-card{
  background: inherit;
  background-color: #3bafda;
}
.income-card{
  background: inherit;
  background-color: #7db1b1;
}
.header-card{
  color: #FFFFFF;
  font-size: 14px;
  height: 150px;
  .title{
    font-weight: 400;
    font-style: normal;
    color: #FFFFFF;
  }
  .num{
    font-size: 36px;
    font-weight: 500;
    margin: 10px 0;
  }
  .item{
    font-size: 12px;
    font-weight: 400;
    margin-bottom: 10px;
    .item-num{
      color: #FFCD00;
    }
  }
}
.content-table{
  margin-top: 20px;

  .table{
    .search{
      display: flex;
      justify-content: space-between;
      margin-bottom: 20px;
    }
  }
}
</style>
